package util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Arrays;

/**
 * 拼音工具类
 * 将汉语拼音的字符转为映射为字母字符串
 */
public class PinyinUtil {
    private static  final HanyuPinyinOutputFormat FORMAT;

    //所有的中文对应的Unicode编码区间
    private static final String CHINESE_PATTERN = "[\\u4E00-\\u9FA5]";

    static {
        FORMAT = new HanyuPinyinOutputFormat();
        //设置转换后的英文字母为全小写
        FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //设置转换后的英文字母是否带音调
        FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //特殊拼音用v来替代
        FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
    }

    /**
     * 传入一个任意的文件名称，就能将该文件转为字母字符串全拼和首字母小写字符串
     * @param fileName
     * @return
     */
    public static String[] getPinyinByFileName(String fileName){
        //第一个字符串为文件名全拼
        //第二个字符串为首字母
        String[] ret = new String[2];
        StringBuilder allNameAppender = new StringBuilder();
        StringBuilder firstCaseAppender = new StringBuilder();
        for (char c : fileName.toCharArray()){
            //不考虑多音字，就使用一个返回值作为参数
            try {
                String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c,FORMAT);
                if (pinyins == null || pinyins.length == 0){
                    //碰到非中文字符，直接保留
                    allNameAppender.append(c);
                    firstCaseAppender.append(c);
                }else{
                    //碰到中文字符，取第一个多音字的返回值
                    allNameAppender.append(pinyins[0]);
                    firstCaseAppender.append(pinyins[0].charAt(0));
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                //碰到非中文字符，直接保留
                allNameAppender.append(c);
                firstCaseAppender.append(c);
            }
        }
        ret[0] = allNameAppender.toString();
        ret[1] = firstCaseAppender.toString();
        return ret;
    }

    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        String str1 = "哈哈哈哈哈";
        System.out.println(Arrays.toString(getPinyinByFileName(str1)));
        System.out.println("-------------------------------------");
        String str2 = "哈1哈2哈3哈4哈";
        System.out.println(Arrays.toString(getPinyinByFileName(str2)));
    }

    /**
     * 判断给定的字符串是否包含中文
     * @param str
     * @return
     */
    public static boolean containsChinese(String str) {
        return str.matches(".*" + CHINESE_PATTERN + ".*");
    }
}
